package com.bl.student.service.biz.hx.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.dao.redis.auth.HxAuthDao;
import com.bl.student.service.biz.hx.HxAuthService;
import com.bl.student.tp.hx.auth.HxAuthApi;
import com.bl.student.tp.hx.auth.HxAuthResponse;
import com.google.common.base.Optional;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yujingyi on 2017/7/26.
 */
@Service
@Log4j2
public class HxAuthServiceImpl implements HxAuthService {

    @Autowired
    HxAuthApi hxAuthApi;

    @Autowired
    HxAuthDao hxAuthDao;

    @Override
    public String getAndSetAccessToken() {

        Optional<String> accessTokenOptional = hxAuthDao.getAccessToken();
        if (accessTokenOptional.isPresent()) {
            return accessTokenOptional.get();
        }

        Optional<HxAuthResponse> hxAuthResponseOptional = hxAuthApi.getAuthToken();
        if (!hxAuthResponseOptional.isPresent() &&
                Strings.isNotBlank(hxAuthResponseOptional.get().getAccess_token())) {
            log.error("get hx access token failed!");
            throw new CommonServiceException(ApiResponseCode.HX_AUTH_FAILED.getCode(), ApiResponseCode.HX_AUTH_FAILED.getMsg());
        }

        HxAuthResponse hxAuthResponse = hxAuthResponseOptional.get();

        hxAuthDao.setAccessToken(hxAuthResponse.getAccess_token(), hxAuthResponse.getExpires_in());

        return hxAuthResponse.getAccess_token();
    }

}
